import Cookies from "js-cookie";
import { refreshAccessToken } from "../api/user";
const TokenKey = "cloud_learning_front_token";
const RefreshTokenKey = "cloud_learning_front_refresh_token";
const RefreshTokenKeyExpireDate = "cloud_learning_front_refresh_token_expire_date";

export function getExpireTime() {
    // token刷新时间
    return 3300000;
}

export function getRefreshTokenKeyExpireDate() {
    return Cookies.get(RefreshTokenKeyExpireDate);
}

export function getToken() {
    // 用户登录token
    return Cookies.get(TokenKey);
}

export function refreshAccessTokenSetTimeout(timestamp) {
    clearTimeout(window.interval);
    window.interval = setTimeout(() => {
        // eslint-disable-next-line no-use-before-define
        refreshTokenMethod();
    }, timestamp);
}

export function setToken(data) {
    const expireData = new Date().getTime() + data.accessToken.expiresIn * 1000;
    Cookies.set(RefreshTokenKeyExpireDate, expireData);
    Cookies.set(RefreshTokenKey, data.refreshToken);
    refreshAccessTokenSetTimeout(getExpireTime());
    return Cookies.set(TokenKey, data.accessToken.value);
}

export function removeToken() {
    Cookies.remove(RefreshTokenKey);
    Cookies.remove(RefreshTokenKeyExpireDate);
    localStorage.clear();
    return Cookies.remove(TokenKey);
}

export function refreshTokenMethod() {
    const refreshToken = Cookies.get(RefreshTokenKey);
    if (!refreshToken) {
        return;
    }
    refreshAccessToken({ refreshToken: refreshToken }, res => {
        const accessToken = { expiresIn: res.expires_in, value: res.access_token };
        const refreshToken = res.refresh_token;
        refreshAccessTokenSetTimeout(getExpireTime());
        setToken({ accessToken: accessToken, refreshToken: refreshToken });
    }).catch(() => {});
}

// 刷新Token
export function refreshToken() {
    const tokenKeyExpireDate = getRefreshTokenKeyExpireDate()
    if (tokenKeyExpireDate) {
        const resetTimer = Math.floor(Number(tokenKeyExpireDate) - new Date().getTime())
        if (resetTimer <= 600000) {
            refreshAccessTokenSetTimeout(15)
        }
    }
}import strongUtils from "../util/storageUtils";
const currentUserKey = "cloud-learning-member";

export function setUser(data) {
    return strongUtils.setJson(currentUserKey, data)
}

export function getUser() {
    const user = strongUtils.getJson(currentUserKey)
    if (user) {
        return user
    }
    return undefined
}

export function deleteUser() {
    strongUtils.remove(currentUserKey);
}